Executing code dynamically is security-sensitive. It has led in the past to the following vulnerabilities:
Some APIs enable the execution of dynamic code by providing it as strings at runtime. These APIs might be useful in some very specific
meta-programming use-cases. However most of the time their use is frowned upon because they also increase the risk of maliciously Injected Code. Such attacks can either run on the server or in the client (example:
XSS attack) and have a huge impact on an application’s security.
This rule marks for review each occurrence of such dynamic code execution. This rule does not detect code injections. It only highlights the use of
APIs which should be used sparingly and very carefully.
Ask Yourself Whether
- the executed code may come from an untrusted source and hasn’t been sanitized.
- you really need to run code dynamically.
There is a risk if you answered yes to any of those questions.
Recommended Secure Coding Practices
Allowing users to execute code dynamically generally creates more problems than it solves.
Anything that can be done via dynamic code execution can usually be done via a language’s native SDK and static code. Therefore, our suggestion is
to avoid executing code dynamically. If the application requires the execution of dynamic code, additional security measures must be taken.
When the untrusted parameters are expected to contain operators, function names or other reflection-related values, best practices would encourage
using an allow list. This one would contain a list of accepted safe values that can be used as part of the dynamic code.
When receiving an untrusted parameter, the application would verify its value is contained in the configured allow list. If it is present, the
parameter is accepted. Otherwise, it is rejected and an error is raised.
Another similar approach is using a binding between identifiers and accepted values. That way, users are only allowed to provide identifiers, where
only valid ones can be converted to a safe value.
Sensitive Code Example
import Foundation
private func sayHello(_ role: String) {
if let script = NSAppleScript(source: "say \"Hello \(role)\"") { // Sensitive
var error: NSDictionary?
script.executeAndReturnError(&error)
}
}
Compliant Solution
import Foundation
enum Role: String {
case User = "User"
case Admin = "Admin"
}
private func sayHello(_ role: Role) {
if let script = NSAppleScript(source: "say \"Hello \(role.rawValue)\"") {
var error: NSDictionary?
script.executeAndReturnError(&error)
}
}
See